package com.example.myblog01.aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//日志类  用来打印日志
@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //    定义切点  拦截web下面的所有的类进行拦截
    @Pointcut("execution(* com.example.myblog01.web.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void dobefore(JoinPoint joinPoint) {
//        打印当前的信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes. getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint. getSignature(). getDeclaringTypeName()+ "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod,args);
        logger.info( "Request : "+ requestLog);
        logger.info("--------------DoBefore-------------");

    }

    @After("log()")
    public void doAfter() {
        logger.info("--------------doAfter-------------");
    }

    //    捕获方法返回的内容
    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterRuturn(Object result) {
        logger.info("Result : "+result);
    }


    //    写一个类 用来返回当前调用的方法 路径等信息
    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

    }
}
